package com.itheima.mobile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

/**
 * @description:
 * @author: dalao
 * @date: 2020/4/12-21:38
 * @Version: 1.0.0
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    @Reference
    private MemberService memberService;
    @Autowired
    private JedisUtils jedisUtils;
    @RequestMapping("/check")
    public Result check(HttpServletRequest request, @RequestBody LoginInfo loginInfo){
//        获取前端验证码
        String validateCode = loginInfo.getValidateCode();
//        获取redis存储的验证码
        String redisCode = loginInfo.getTelephone() + RedisMessageConstant.SENDTYPE_LOGIN;
        String code = jedisUtils.get(redisCode);
//        判定
        if(code==null&&!code.equals(validateCode)){
            return Result.ERROR("验证码错误");
        }

        Member member = memberService.findById(loginInfo.getTelephone());
        if(member==null){
            member=new Member();
            member.setPhoneNumber(loginInfo.getTelephone());
            member.setRegTime(new Date());
            member=memberService.add(member);
        }
//        登录成功存储到session
//        request.getSession().setAttribute("member", JSON.toJSONString(member));
//        储存用户的登录状态
//        生成token
        String token = UUID.randomUUID().toString() + member.getId();
//        储存到redis
        jedisUtils.setex(token,60*60*8,JSON.toJSONString(member));
        return Result.OK(MessageConstant.LOGIN_SUCCESS,token);


    }
}
